package com.example.web.controller;

import cn.dev33.satoken.stp.StpUtil;
import com.example.common.constant.RedisConstant;
import com.example.common.redis.RedisUtils;
import com.example.common.response.R;
import com.example.common.utils.FileUtils;
import com.example.system.domain.entity.User;
import com.example.system.domain.model.FileParam;
import com.example.system.service.ImageService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import java.util.ArrayList;
import java.util.List;

/**
 * 上传操作
 **/
@RestController
@Api(value = "上传管理", tags = {"上传管理"})
@RequestMapping(value = "/upload", method = {RequestMethod.POST, RequestMethod.GET})
public class UploadController {

    @Autowired
    public ImageService imageService;
    @Autowired
    private RedisUtils redisUtils;
    @Autowired
    private FileUtils fileUtils;

    /* 图片 */
    @ResponseBody
    @ApiOperation("上传图片")
    @RequestMapping(value = "/image", method = RequestMethod.POST, consumes = "multipart/form-data")
    public R<String> image(FileParam files) {
        MultipartFile file = files.getFiles()[0];
        String account = (String) StpUtil.getLoginId();
        if (file.isEmpty()) {
            return R.fail("文件为空");
        }
        String uploadFilePath = fileUtils.uploadImageUtil(file);
        User user = new User();
        user.setAccount(account);
        user.setImage(uploadFilePath);
        imageService.changeImage(user);
        return R.ok("头像更换成功");
    }

    /* 附件 */
    @ResponseBody
    @ApiOperation("上传附件")
    @RequestMapping(value = "/file", method = RequestMethod.POST, consumes = "multipart/form-data")
    public R<String> file(FileParam files) {
        List<String> stringList = new ArrayList<>();
        fileUtils.uploadFileUtil(files.getFiles(), stringList);
        String account = (String) StpUtil.getLoginId();
        String k = RedisConstant.Project_Files + account;
        long time = RedisConstant.Project_Files_TIme;
        redisUtils.set(k, stringList, time);
        return R.ok(null);
    }

}
